package com.sdtv.basemodule.http.interceptors;

import com.blankj.utilcode.util.NetworkUtils;

import java.io.IOException;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.http.interceptors
 * @ClassName: CacheInteceptor
 * @Description: 网络数据缓存策略  -有网络使用网络数据 没网络使用缓存数据
 * @Author: 小郭同学
 * @CreateDate: 2019-06-20 15:10
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class CacheInteceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (NetworkUtils.isConnected()) {
            Response response = chain.proceed(request);
            // read from cache for 0 s  有网络不会使用缓存数据
            int maxAge = 10;
            return response.newBuilder()
                    .build();
        } else {
            //无网络时强制使用缓存数据
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
            Response response = chain.proceed(request);
            int maxStale = 60 * 60 * 24 * 3;
            return response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
    }
}
